<template>
  <Card title="交接业务对接人">
    <header>
      <el-row>
        <el-col :span="3">提交人：{{info.submit}}</el-col>
        <el-col :span="5">提交时间：{{info.submitTime}}</el-col>
        <el-col :span="5">提交人部门：{{info.submitDapart}}</el-col>
        <el-col :span="11">现业务对接人：{{info.nowSubmitPerson}}</el-col>
      </el-row>
    </header>
    <p style="margin-bottom: 20px">
      交接业务对接人：
      <span v-if="processId">{{info.newSubmitPerson}}</span>
      <UserSelect v-else ref="userSelect"
        v-model="user.userIdStr" placeholder="请输入对接人姓名"
        @onSelected="handleUserSelect" />
    </p>
    <basic-table
        :showActionCol="supplierIds.length>0"
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :tableHeight="460"
        :actionColWidth="100"
        :showPagination="false"
        :actionRender="renderTableBtnAction"
      />
    <p class="actions">
      <el-button v-if="supplierIds.length>0" @click="handleConfirm()" type="primary">确认提交</el-button>
      <el-button @click="handleBack()">{{supplierIds.length>0?'取消':'返回上一层'}}</el-button>
    </p>
  </Card>
</template>

<script>
import { mapState } from 'vuex';
import UserSelect from '@/components/commodity/UserRemoteSelect'
import BasicTable from '@/components/supplier/BasicTable';
import Dict from '@/mixins/supplier/dict';
import {
  batchHandoverBusinessContact,
  queryBusinessContacts, // 根据供应商ids查询供应商业务对接人
} from '@/api/supplier/management/qualifiedSupplier';
// 根据审批流id, 查询审批页面的业务对接人详情
import { queryBusinessDetail } from '@/api/supplier/management/pendingApproval';

export default {
  mixins: [Dict],
  components: {
    UserSelect,
    BasicTable,
  },
  data () {
    const { id = 0, processId = 0 } = this.$route.query
    let supplierIds = []
    if (typeof id === 'string') {
      supplierIds.push(parseInt(id, 10))
    } else {
      supplierIds = id
    }
    return {
      id,
      processId,
      fromPageName: '',
      tableInfo: {
        list: [],
        selection: [],
        columns: [],
        loading: false
      },
      user: {
        userId: 0,
        userIdStr: '',
        userName: '',
      },
      info: {},
      supplierIds
    }
  },
  computed: {
    ...mapState('supplier/dict', [
      'dictData',
      'dictOptData',
    ]),
  },
  created () {
    if (!this.supplierIds.length && !this.processId) {
      this.handleBack()
      return
    }
    this.init();
  },
  watch: {
    dictOptData: {
      handler (newVal) {
        if (!newVal || !newVal[233]) {
          return
        }

        this.tableInfo.columns = [
          { title: '供应商代码', key: 'supplierCode' },
          { title: '供应商名称', key: 'supplierName' },
          { title: '主营品类代码', key: 'mainCategoryCode' },
          { title: '主营品类', key: 'mainCategory' },
          { title: '现业务对接人', key: 'businessContactName' },
          { title: '采购归属',
            key: 'belongDepartment',
            formatter  (row, column, cellValue, index) {
              if (cellValue) {
                const data = newVal[233].find((item) => item.value == cellValue)
                if (data) {
                  return newVal[233].find((item) => item.value == cellValue)['label']
                }
              }
              return ''
            }
          },
          { title: '管理区域', key: 'managementAreaName' },
        ]
      },
      immediate: true,
      deep: true
    },
  },
  mounted () {
  },
  methods: {
    init () {
      if (this.processId) {
        this.queryBusinessDetail()
      } else {
        this.queryBusinessContacts()
      }
    },
    async queryBusinessDetail () {
      const { processId } = this
      this.tableInfo.loading = true
      const resp = await queryBusinessDetail({ processId })
      this.tableInfo.loading = false
      if (resp && resp.status === '0') {
        const {
          submit,
          submitTime,
          submitDapart,
          nowSubmitPerson,
          newSubmitPerson,
          supplierList
        } = resp.result
        this.info = {
          nowSubmitPerson,
          submit,
          submitDapart,
          submitTime,
          newSubmitPerson
        }
        this.tableInfo.list = supplierList
      }
    },
    async queryBusinessContacts () {
      const { supplierIds } = this
      if (supplierIds.length === 0) {
        this.info.submitTime = ''
        this.info.submitDapart = ''
        this.info.nowSubmitPerson = ''
        this.tableInfo.list = []
        return
      }
      this.tableInfo.loading = true
      const resp = await queryBusinessContacts({ supplierIds })
      this.tableInfo.loading = false
      if (resp && resp.status === '0') {
        const {
          nowSubmitPerson,
          submit,
          submitDapart,
          submitDapartId,
          submitId,
          submitTime,
          supplierList,
        } = resp.result
        this.info = Object.assign({}, {
          nowSubmitPerson,
          submit,
          submitDapart,
          submitDapartId,
          submitId,
          submitTime
        })
        this.tableInfo.list = supplierList
      } else {
        this.handleBack()
      }
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div>
        <el-button type="text" nativeOnClick={() => { this.handleDelete(row) }}>删除</el-button>
      </div>
    },
    handleUserSelect (data) {
      // const { userId, userIdStr, userName } = data
      this.user = data
      // console.log('userId', userId)
      // console.log('userIdStr', userIdStr)
      // console.log('userName', userName)
    },
    handleDelete (row) {
      this.$confirm('放弃交接该供应商, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.supplierIds = this.supplierIds.filter(item => item != row.supplierId)
        this.init()
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
    async handleConfirm () {
      // 确认提交
      if (!this.user || !this.user.userId) {
        this.$message.error('请选择交接业务对接人')
        return
      }
      const resp = await batchHandoverBusinessContact({
        businessContact: this.user.userId,
        businessContactName: this.user.userName,
        supplierList: this.tableInfo.list,
        hrAreaId: this.user.hrAreaId
      })
      if (resp && resp.status === '0') {
        this.$message.success(resp.result || '操作成功')
        this.handleBack()
      }
    },
    handleBack () {
      this.tableInfo.list = []
      this.$router.go(-1)
    },
  },
}
</script>

<style scoped>
header {
  padding: 10px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #f1f1f1;
}
.actions {
  margin-top: 20px;
  text-align: center;
}
</style>
